#!/bin/sh


#使用此脚本首先应使用root帐户安装cronolog
#yum -y install cronolog
#此脚本可以实现以start和stop方式启动或关闭，并且日志将按日期方式输出
#wget http://download-ib01.fedoraproject.org/pub/epel/6/x86_64/Packages/c/cronolog-1.6.2-10.el6.x86_64.rpm
#rpm -ivh cronolog-1.6.2-10.el6.x86_64.rpm

CRONOLOG_INSTALLED=0
CRONOLOG_PATH=
check_cronolog() {
    # PS some OS location: /usr/sbin/cronolog OR /usr/local/sbin/cronolog OR /usr/bin/cronolog(ubuntu)
    local cronolog_path=/usr/local/sbin/cronolog
    if [ ! -f "$cronolog_path" ]; then
      cronolog_path=/usr/sbin/cronolog
      if [ ! -f "$cronolog_path" ]; then
        cronolog_path=/usr/bin/cronolog
        if [ ! -f "$cronolog_path" ]; then
          wget http://download-ib01.fedoraproject.org/pub/epel/6/x86_64/Packages/c/cronolog-1.6.2-10.el6.x86_64.rpm
          rpm -ivh cronolog-1.6.2-10.el6.x86_64.rpm
          if [ $CRONOLOG_INSTALLED -eq 0 ]; then
            CRONOLOG_INSTALLED=1
            return check_cronolog
          else
            return 0
          fi
        fi
      fi
    fi
    CRONOLOG_PATH=$cronolog_path
    return 1
}
check_cronolog
if [ $? -eq 0 ]; then
  echo 'no found cronolog,please execute > yum -y install cronolog'
  exit -1
fi

JARPATH=$(cd "$(dirname "$0")";pwd)
JARNAME=""

##递归遍历指定目录
traverse_dir()
{
    filepath=$1

    for file in `ls -a $filepath`
    do
        if [ -d ${filepath}/$file ]
        then
            if [[ $file != '.' && $file != '..' ]]
            then
                #递归
                #traverse_dir ${filepath}/$file
                echo ${filepath}/$file
            fi
        else
            #调用查找指定后缀文件
            check_suffix ${filepath}/$file
        fi
    done
}


##获取后缀jar的文件
check_suffix()
{
    file=$1

    if [ "${file##*.}"x = "jar"x ];then
        echo $file
                JARNAME=$file
    fi
}

#测试指定目录  /data_output/ci/history
#traverse_dir $(cd "$(dirname "$0")";pwd)
traverse_dir $JARPATH

echo $JARNAME

#移除文件后缀名
echo ${JARNAME%".jar"}
JARNAME=${JARNAME%".jar"}

#移除文件路径,得到文件名
echo ${JARNAME#$JARPATH\/}
JARNAME=${JARNAME#$JARPATH\/}
echo $JARNAME

cd $JARPATH

case "$1" in

  start)
    nohup java -Xmx128m -jar $JARPATH/$JARNAME.jar 2>&1 | $CRONOLOG_PATH ./logs/nohup_%Y%m%d.log &
    echo $[$!-1] > $JARPATH/$JARNAME.pid
    ;;

  stop)
    kill -9  `cat $JARPATH/$JARNAME.pid`
    rm -rf $JARPATH/$JARNAME.pid
    ;;

  restart)
    $0 stop
    sleep 1
    $0 start
    ;;

  *)
    echo "Usage: run.sh {start|stop|restart}"
    ;;

esac

exit 0

